
from os import path
import logging
import json
import paho.mqtt.client as paho
T_TOPIC = "/test"

class MqttClient:
    def __init__(self, config: dict) -> None:
        global _log
        self._config = config
        self.ip = config["host"]
        self.port = config["port"]
        _log = logging.getLogger('mqtt')
        self._client = paho.Client(protocol=paho.MQTTv311)
        self._client.on_connect = lambda _, __, ____, rc: self.on_connect_cb(rc)
        self._client.on_message = self._on_message_cb
        self._topic = T_TOPIC
        self.name_list = []

    def on_connect_cb(self, rc: int):
        _log.info("Connected mqtt broker %s with result: %d", self._config["host"], rc)

    
    def send_msg(self,  msg: dict, qos:int = 0,topic: str = T_TOPIC):
        topic = self._topic
        payload = json.dumps(msg)
        print(f"mqtt发送数据topic:{topic},payload:{payload}")
        _log.debug("topic:",topic,"payload:",payload)
        self._client.publish(topic, payload, qos)


    def _on_message_cb(self, client, userdata, msg):
        payload = json.loads(msg.payload.decode("utf-8"))
        self._check_name(payload)
        pass
    #检查payload中存在的名字
    def _check_name(self,payload):
        if payload["newname"] in self.name_list:
            #删除名字
            self.name_list.remove(payload["newname"])
            #输出剩余名字
            print("剩余名字：",self.name_list)
        pass

    def start(self):
        self._client.username_pw_set(username="juji1234", password="juji1234")
        self._client.connect(self._config["host"], self._config["port"], 60)
        self._client.loop_start()
        self._client.subscribe(self._topic)
    
    def stop(self):
        self._client.loop_stop()

if __name__ == "__main__":
    CONFIG = {"host":"172.27.0.100","port":1883}
    mqtt_client = MqttClient(CONFIG)
    namelist = []
    #输入文件名
    # name_file = input("请输入文件名：")
    with open(path.join(path.dirname(__file__), "name_list_2829.txt"), "r", encoding="utf-8") as f:
        for line in f.readlines():
            namelist.append(line.strip())
    mqtt_client.name_list = namelist
    #请输入订阅主题
    topic = input("请输入订阅主题：")
    mqtt_client._topic = topic
    mqtt_client.start()
    while True:
        pass

